/*
 * Copyright 2020-2023 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.springframework.security.oauth2.server.authorization.web.authentication;

import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import jakarta.servlet.http.HttpServletRequest;

import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.oauth2.core.OAuth2ErrorCodes;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponseType;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.security.oauth2.core.endpoint.PkceParameterNames;
import org.springframework.security.oauth2.core.oidc.OidcScopes;
import org.springframework.security.oauth2.server.authorization.authentication.OAuth2AuthorizationCodeRequestAuthenticationException;
import org.springframework.security.oauth2.server.authorization.authentication.OAuth2AuthorizationCodeRequestAuthenticationToken;
import org.springframework.security.oauth2.server.authorization.web.OAuth2AuthorizationEndpointFilter;
import org.springframework.security.web.authentication.AuthenticationConverter;
import org.springframework.security.web.util.matcher.AndRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;

/**
 * Attempts to extract an Authorization Request from {@link HttpServletRequest}
 * for the OAuth 2.0 Authorization Code Grant and then converts it to
 * an {@link OAuth2AuthorizationCodeRequestAuthenticationToken} used for authenticating the request.
 *
 * @author Joe Grandja
 * @since 0.1.2
 * @see AuthenticationConverter
 * @see OAuth2AuthorizationCodeRequestAuthenticationToken
 * @see OAuth2AuthorizationEndpointFilter
 */
public final class OAuth2AuthorizationCodeRequestAuthenticationConverter implements AuthenticationConverter {
	private static final String DEFAULT_ERROR_URI = "https://datatracker.ietf.org/doc/html/rfc6749#section-4.1.2.1";
	private static final String PKCE_ERROR_URI = "https://datatracker.ietf.org/doc/html/rfc7636#section-4.4.1";
	//注意此处创建的AnonymousAuthenticationToken是已认证状态
	private static final Authentication ANONYMOUS_AUTHENTICATION = new AnonymousAuthenticationToken(
			"anonymous", "anonymousUser", AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS"));
	//oidc认证请求匹配器
	private static final RequestMatcher OIDC_REQUEST_MATCHER = createOidcRequestMatcher();
	// http://127.0.0.1:8083/authorizationProject/oauth2/authorize?response_type=code&client_id=clientTest
	// &scope=read%20write%20profile%20openid&state=QNt5ubBO0h-ubLx4Jb1D5WT2UqEWCezaCyf_oritfLY%3D
	// &redirect_uri=http://127.0.0.1:8081/clientProject/login/oauth2/code/clientService
	// &nonce=O3iSJ8BMMTrLOXLi0ZZzl7Rx1Y-Dn1aI9-x4fFPRkn0
	@Override
	public Authentication convert(HttpServletRequest request) {
		//不是get请求并且不是oidc认证请求直接返回null(授权页面点击登录按钮时发送的授权请求符合该条件)
		if (!"GET".equals(request.getMethod()) && !OIDC_REQUEST_MATCHER.matches(request)) {
			return null;
		}

		//走到此处说明请求是get请求{client获取授权码发过来的请求} 或者 不是get请求但是oidc请求

        //将request中的参数信息解析为键值对集合
		MultiValueMap<String, String> parameters = OAuth2EndpointUtils.getParameters(request);

		// response_type (REQUIRED)
		// response_type必须，且只能有一个 且授权类型必须是code
		String responseType = request.getParameter(OAuth2ParameterNames.RESPONSE_TYPE);
		if (!StringUtils.hasText(responseType) ||
				parameters.get(OAuth2ParameterNames.RESPONSE_TYPE).size() != 1) {
			throwError(OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.RESPONSE_TYPE);
		} else if (!responseType.equals(OAuth2AuthorizationResponseType.CODE.getValue())) {
			throwError(OAuth2ErrorCodes.UNSUPPORTED_RESPONSE_TYPE, OAuth2ParameterNames.RESPONSE_TYPE);
		}
        //request请求地址，作为授权服务器地址
		String authorizationUri = request.getRequestURL().toString();

		// client_id (REQUIRED)
		// client_id必须，且只能有一个
		String clientId = parameters.getFirst(OAuth2ParameterNames.CLIENT_ID);
		if (!StringUtils.hasText(clientId) ||
				parameters.get(OAuth2ParameterNames.CLIENT_ID).size() != 1) {
			throwError(OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.CLIENT_ID);
		}
        //当前认证上下文，如果已经认证，则取出认证结果，否则设置为匿名认证（不管是哪种，二者均已是认证状态 注意此时还未经过匿名过滤器处理）
		Authentication principal = SecurityContextHolder.getContext().getAuthentication();
		if (principal == null) {
			principal = ANONYMOUS_AUTHENTICATION;
		}

		// redirect_uri (OPTIONAL)
		// redirect_uri可选，最多一个
		String redirectUri = parameters.getFirst(OAuth2ParameterNames.REDIRECT_URI);
		if (StringUtils.hasText(redirectUri) &&
				parameters.get(OAuth2ParameterNames.REDIRECT_URI).size() != 1) {
			throwError(OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.REDIRECT_URI);
		}

		// scope (OPTIONAL)
		Set<String> scopes = null;
		// scope可选，最多一个
		String scope = parameters.getFirst(OAuth2ParameterNames.SCOPE);
		if (StringUtils.hasText(scope) &&
				parameters.get(OAuth2ParameterNames.SCOPE).size() != 1) {
			throwError(OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.SCOPE);
		}
		// 如果存在则按照空格(%20)进行切分
		if (StringUtils.hasText(scope)) {
			scopes = new HashSet<>(
					Arrays.asList(StringUtils.delimitedListToStringArray(scope, " ")));
		}

		// state (RECOMMENDED)
		// state是一个可选，但是推荐使用的参数。主要用于客户端确保OAuth2.x中回调那一步时，是真正的授权服务器回调给自己
		String state = parameters.getFirst(OAuth2ParameterNames.STATE);
		// 使用方式为：在开始请求授权时，客户端传给授权服务器的一个随机字符串，然后授权服务器回调时，会原封不动将这个参数传给客户端，
		// 此时，客户端可以比较这两个值是否一致，只有一致时，表示这个回调来自真实的授权服务器，这个授权码是可信的
		if (StringUtils.hasText(state) &&
				parameters.get(OAuth2ParameterNames.STATE).size() != 1) {
			throwError(OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.STATE);
		}
        //code_challenge && code_challenge_method
		//这俩是后面新加的参数，对于一般的OAuth2授权流程是不需要的。它主要是针对公共客户端的授权，一般指前端应用，不方便存储密钥的客户端
		//目的：用于授权服务器确定，使用获取code和换取token的同一个客户端。 客户端none方式时会默认帮我们生成传递该值
		//使用方式：
		//1. 本地生成一个随机字符串code_verifier，使用code_challenge_method算法，得到一个code_challenge
		//2. 请求授权码时，将这两个值，都传给授权服务器，授权服务器会保存两个值code_challenge_method code_challenge
		//3. 等客户端拿着code获取token时会将code_verifier传递到授权服务器，然后进行验证
		// code_challenge (REQUIRED for public clients) - RFC 7636 (PKCE)
		String codeChallenge = parameters.getFirst(PkceParameterNames.CODE_CHALLENGE);
		if (StringUtils.hasText(codeChallenge) &&
				parameters.get(PkceParameterNames.CODE_CHALLENGE).size() != 1) {
			throwError(OAuth2ErrorCodes.INVALID_REQUEST, PkceParameterNames.CODE_CHALLENGE, PKCE_ERROR_URI);
		}

		// code_challenge_method (OPTIONAL for public clients) - RFC 7636 (PKCE)
		String codeChallengeMethod = parameters.getFirst(PkceParameterNames.CODE_CHALLENGE_METHOD);
		if (StringUtils.hasText(codeChallengeMethod) &&
				parameters.get(PkceParameterNames.CODE_CHALLENGE_METHOD).size() != 1) {
			throwError(OAuth2ErrorCodes.INVALID_REQUEST, PkceParameterNames.CODE_CHALLENGE_METHOD, PKCE_ERROR_URI);
		}

		Map<String, Object> additionalParameters = new HashMap<>();
		parameters.forEach((key, value) -> {
			if (!key.equals(OAuth2ParameterNames.RESPONSE_TYPE) &&
					!key.equals(OAuth2ParameterNames.CLIENT_ID) &&
					!key.equals(OAuth2ParameterNames.REDIRECT_URI) &&
					!key.equals(OAuth2ParameterNames.SCOPE) &&
					!key.equals(OAuth2ParameterNames.STATE)) {
				additionalParameters.put(key, (value.size() == 1) ? value.get(0) : value.toArray(new String[0]));
			}
		});
        //将请求参数包装成OAuth2AuthorizationCodeRequestAuthenticationToken对象返回 注意principal是Authentication对象，里面包含是否已认证信息
		//但是OAuth2AuthorizationCodeRequestAuthenticationToken对象本身的认证状态为未认证
		return new OAuth2AuthorizationCodeRequestAuthenticationToken(authorizationUri, clientId, principal,
				redirectUri, state, scopes, additionalParameters);
	}

	private static RequestMatcher createOidcRequestMatcher() {
		//post请求
		RequestMatcher postMethodMatcher = request -> "POST".equals(request.getMethod());
		//请求参数中response_type不为null
		RequestMatcher responseTypeParameterMatcher = request ->
				request.getParameter(OAuth2ParameterNames.RESPONSE_TYPE) != null;
		//请求参数中scope不为null，且包含openid
		RequestMatcher openidScopeMatcher = request -> {
			String scope = request.getParameter(OAuth2ParameterNames.SCOPE);
			return StringUtils.hasText(scope) && scope.contains(OidcScopes.OPENID);
		};
		//三者均满足才会返回true
		return new AndRequestMatcher(
				postMethodMatcher, responseTypeParameterMatcher, openidScopeMatcher);
	}

	private static void throwError(String errorCode, String parameterName) {
		throwError(errorCode, parameterName, DEFAULT_ERROR_URI);
	}

	private static void throwError(String errorCode, String parameterName, String errorUri) {
		OAuth2Error error = new OAuth2Error(errorCode, "OAuth 2.0 Parameter: " + parameterName, errorUri);
		throw new OAuth2AuthorizationCodeRequestAuthenticationException(error, null);
	}

}
